﻿module Sustainalytics.Portfolio {

    import Common = Sustainalytics.Common;

    export interface ISystemPortfolioService {

        getAllAutomaticSystemPortfolios(userId: string, accountId: string);
        getRelatedSystemPortfolios(id: string, userId: string, accountId: string);
        savePortfolio: (portfolio: PortfolioDto, relatedUniverses: RelatedUniverses[]) => any;
        getPortfolioCount(portfolioFilterDto: Sustainalytics.Portfolio.PortfolioFilterDto, accountId: string, userId: string): ng.IPromise<PortfolioListDto>;
    }

    export class SystemPortfolioService implements ISystemPortfolioService {

        private staticObjects: Common.IStaticObjects;
        private urlBase: string;
        constructor(
            private $q: ng.IQService,
            private $http: ng.IHttpService,
            private notificationFactory: Common.INotificationFactory,
            staticObjects: Common.IStaticObjects,
            private ClaimsAuthorizationService: Sustainalytics.Claims.ClaimsAuthorizationService) {
            
            this.staticObjects = staticObjects;
            this.urlBase = staticObjects.portfolioBaseUrl;

        }

        getAllAutomaticSystemPortfolios(userId:string, accountId:string) {
            var def = this.$q.defer();
            var ctx = this;
            var params = $.param({
                userId: userId,
                onlyAutomatic:true,
                includeAllFields: false

            });

            var url = ctx.urlBase + "/api/v1/systemportfolios?" + params;
            var promise = ctx.$http.get(url);

            promise.success(
                data => {
                    def.resolve(data);
                }).error(
                () => {
                    def.reject();
                });

            return def.promise;
        }

        getRelatedSystemPortfolios(id: string, userId: string, accountId: string) {
            var def = this.$q.defer();
            var ctx = this;
            var params = $.param({
                userId: userId
            });

            var url = ctx.urlBase + "/api/v1/systemportfolios/"+id+"?" + params;
            var promise = ctx.$http.get(url);

            promise.success(
                data => {
                    def.resolve(data);
                }).error(
                () => {
                    def.reject();
                });

            return def.promise;
        }

        savePortfolio(portfolio: PortfolioDto, relatedUniverses: RelatedUniverses[]) {
            var def = this.$q.defer();
            var url: string;
            var httpConfig: ng.IRequestConfig;

            if (portfolio.id!=undefined) {
                url = this.urlBase + "/api/v1/systemportfolios/" + portfolio.id;
                httpConfig = { method: "PATCH", url: url, data: relatedUniverses  };
            }
            else {
                url = this.urlBase + "/api/v1/systemportfolios/";
                var relatedUniversesTemp = relatedUniverses.map((item) => {
                    var result = new RelatedUniverses();
                    result.id = item.id;
                    result.name = item.name;
                    return result;
                });

                httpConfig = { method: "POST", url: url, data: { name: portfolio.name, relatedUniverses:relatedUniversesTemp } }; 
            }
            var promise = this.$http(httpConfig);

            promise.success(data => {
                    this.showMessage("Portfolio saved successfully!");
                    def.resolve(data);
                })
                .error(err => {
                    this.showError(err);
                    def.reject();
                });

            return def.promise;
        }


        private showError(err) {
            var ctx = this;
            if (err && err["errorCode"]) {
                ctx.notificationFactory.error("", ctx.staticObjects.getErrorMesageByStatusCode(err["errorCode"], err["errorCode"]));
            } else {
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode());
            }
            
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }

        getPortfolioCount(portfolioFilterDto: Sustainalytics.Portfolio.PortfolioFilterDto, accountId: string, userId: string): ng.IPromise<any> {
            var def = this.$q.defer();

            var options = new Common.ListOptions();
            options.skip = 0;
            options.take = 1;
            options.orderBy =["DateCreated"];
            options.orderAscending = true;
            options.includeAllFields = false;
            options.getCount = true;

            var params = $.param({
                isMyPortfolio: portfolioFilterDto.isMyPortfolio,
                namePortfolio: portfolioFilterDto.namePortfolio,
                sharingStatus: portfolioFilterDto.sharingStatus,
                portfolioType: portfolioFilterDto.portfolioType,
                accountId: accountId,
                userId: userId,
                isNameEqual:true,
                listOptions: options
            });

            var url = this.urlBase + "/api/v1/portfolios?" + params;
            var promise = this.$http.get(url);

            promise.success(data => { def.resolve(data); })
                    .error(err => { this.showError(err); def.reject(); });

            return def.promise;
        }
    }

    angular.module(portfolioModuleName).service("SystemPortfolioService",
        ["$q", "$http", "notificationFactory", "staticObjects", "ClaimsAuthorizationService", SystemPortfolioService]);
}